import { Common, Router } from "../../utils/common.js";
const util = require('../../utils/util.js')
Page({
  data: {
    date: "2017-01-01",
    pickEndDate: "2025-12-31",
    src: "/style/images/upload.png",
    neu: -1,
    sex: -1,
    pet: {}, //for save data
    petVali: {}, // for validate
    userInfo: {},
    _id: '' //宠物Id
  },

  onLoad: function (options) {
    let userInfo = wx.getStorageSync("userInfo");
    let that = this
    that.setData({
      userInfo: userInfo
    })
    let endDate = util.formatDate(new Date())
    if (options.pet) {
      that.data.pet = JSON.parse(options.pet)
      that.data.petVali = JSON.parse(options.petVali)
      that.setData({
        pet: that.data.pet,
        petVali: that.data.petVali,
        date: that.data.pet.birthday,
        src: that.data.pet.avatarTmp || "/style/images/upload.png",
        neu: that.data.pet.isNeuter,
        sex: that.data.pet.sex,
        pickEndDate: endDate
      })
      console.log(that.data.pet);
    } else {//add and first coming
      that.data.pet.birthday = "2017-01-01"
      that.data.petVali.birthdayOk = true
      that.setData({
        pickEndDate: endDate
      })
    }
  },
  sexTap: function (e) {
    let val = e.currentTarget.dataset.sexval
    let that = this
    if (val == 1) {
      that.data.pet.sex = 1
      that.setData({
        sex: 1
      })
      that.data.petVali.sexOk = true
    } else if (val == 0) {
      that.data.pet.sex = 0
      that.setData({
        sex: 0
      })
      that.data.petVali.sexOk = true
    }
  },
  neuTap: function (e) {
    let val = e.currentTarget.dataset.neuval
    let that = this
    if (val == 1) {
      that.data.pet.isNeuter = 1
      that.setData({
        neu: 1
      })
      that.data.petVali.neuOk = true
    } else if (val == 0) {
      that.data.pet.isNeuter = 0
      that.setData({
        neu: 0
      })
      that.data.petVali.neuOk = true
    }
  },
  bindDateChange: function (e) {
    this.data.pet.birthday = e.detail.value
    this.setData({
      date: e.detail.value
    })
    this.data.petVali.birthdayOk = true
  },
  getPetName: function (e) {
    this.data.pet.petName = e.detail.value
    console.log("this.data.pet.petName====" + this.data.pet.petName)
    if (this.data.pet.petName) {
      this.data.petVali.petNameOk = true
    } else {
      this.data.petVali.petNameOk = false
    }
    console.log("this.data.petVali.petNameOk==" + this.data.petVali.petNameOk)
  },
  getPetWeight: function (e) {
    this.data.pet.weight = e.detail.value
    console.log("this.data.pet.weight====" + this.data.pet.weight)
    if (this.data.pet.weight) {
      this.data.petVali.weightOk = true
    } else {
      this.data.petVali.weightOk = false
    }
  },
  getPetBreed: function (e) {
    this.data.pet.breed = e.detail.value
    console.log("this.data.pet.breed====" + this.data.pet.breed)
    if (this.data.pet.breed) {
      this.data.petVali.breedOk = true
    } else {
      this.data.petVali.breedOk = false
    }
  },
  getPetFeature: function (e) {
    this.data.pet.feature = e.detail.value
    console.log("this.data.pet.feature====" + this.data.pet.feature)
    if (this.data.pet.feature) {
      this.data.petVali.featureOk = true
    } else {
      this.data.petVali.featureOk = false
    }
  },
  upload: function () {
    let that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        let src = res.tempFilePaths[0];
        that.uploadPic(src);
      }
    })
  },
  /**
   * 上传图片到微信云存储
   */
  uploadPic(src) {
    let filePath = src;
    let suffix = /\.[^\.]+$/.exec(filePath)[0]; // 正则表达式，获取文件扩展名
    wx.cloud.uploadFile({
      cloudPath: "petHeadPic/" + new Date().getTime() + suffix,
      filePath: filePath, // 文件路径
    }).then(res => {
      console.log(res.fileID)
      this.setData({
        src: res.fileID,
        'petVali.avatarOk': true
      })
    }).catch(error => {
      console.log(error)
    })
  },
  saveData: function () {
    // 获取当前年月日
    let date = new Date();
    let myDate = date.toLocaleDateString(); //获取当前日期
    let that = this;
    let petVali = that.data.petVali;
    if (!petVali.petNameOk) {
      Common.myToast("请输入名字", 2000);
      return;
    } else if (!petVali.sexOk) {
      Common.myToast("请选择性别", 2000);
      return;
    } else if (!petVali.birthdayOk) {
      Common.myToast("请输入生日", 2000);
      return;
    } else if (!petVali.weightOk) {
      Common.myToast("请输入体重", 2000);
      return;
    } else if (!petVali.breedOk) {
      Common.myToast("请输入品种", 2000);
      return;
    } else if (!petVali.featureOk) {
      Common.myToast("请输入描述", 2000);
      return;
    } else if (!petVali.neuOk) {
      Common.myToast("请选择是否绝育", 2000);
      return;
    } else if (!petVali.avatarOk) {
      Common.myToast("请上传头像", 2000);
      return;
    }
    let userid = wx.getStorageSync("openid");
    wx.showNavigationBarLoading()
    var pet = {
      petName: this.data.pet.petName, // 宠物名
      birthday: this.data.pet.birthday, // 宠物生日
      avatar: this.data.src, // 头像
      sex: this.data.sex, // 性别
      isNeuter: this.data.neu, // 是否绝育
      weight: this.data.pet.weight, // 体重
      feature: this.data.pet.feature, // 一句描述：爱吃啥，有啥特点
      userid: userid, // 宠物主人用户openid
      userNickName: this.data.userInfo.nickName, //宠物主人用户昵称
      totalEnergy: 0, //历史运动总值
      constellation: this.getAstro( this.data.pet.birthday), //星座
      breed: this.data.pet.breed, // 品种
      isdel: 0, // 是否删除
      levelNo: 0, // 等级
      picLikeCount: 0, //写真集点赞数量
      updateTime: myDate, // 更新日期
      petNo: this.MathRand(), // 卡号
      age: this.getAge(this.data.pet.birthday) // 年龄
    }
    const db = wx.cloud.database();
    if (this.data.pet._id != '' && this.data.pet._id != null) {
      db.collection('p_pets').doc(this.data.pet._id).update({
        data: {
          petName: this.data.pet.petName, // 宠物名
          birthday: this.data.pet.birthday, // 宠物生日
          avatar: this.data.src, // 头像
          sex: this.data.sex, // 性别
          isNeuter: this.data.neu, // 是否绝育
          weight: this.data.pet.weight, // 体重
          feature: this.data.pet.feature, // 一句描述：爱吃啥，有啥特点
          constellation: this.getAstro( this.data.pet.birthday), //星座
          breed: this.data.pet.breed, // 品种
          updateTime: myDate, // 更新日期
          age: this.getAge(this.data.pet.birthday) // 年龄
        }
      }).then(res => {
        wx.switchTab({
          url: '/pages/index/index',
        });
      })
      return;
    }
    db.collection('p_pets').add({
      // data 字段表示需新增的 JSON 数据
      data: pet
    }).then(res => {
      wx.hideNavigationBarLoading()
      var infoStr = JSON.stringify(pet);
      var mURL = encodeURIComponent(infoStr);//把字符串编码为 URI 组件。
      wx.navigateTo({
        url: '../dogaddcomp/dogaddcomp?pet=' + mURL
      })
    })
  },
  // 根据生日的月份和日期，计算星座。
  getAstro(birthday) {
    // 魔羯座(12/22 - 1/19)、水瓶座(1/20 - 2/18)、双鱼座(2/19 - 3/20)、牡羊座(3/21 - 4/20)、
    // 金牛座(4/21 - 5/20)、双子座(5/21 - 6/21)、巨蟹座(6/22 - 7/22)、狮子座(7/23 - 8/22)、
    // 处女座(8/23 - 9/22)、天秤座(9/23 - 10/22)、天蝎座(10/23 - 11/21)、射手座(11/22 - 12/21)
    let date = birthday.substr(5,7); // 这种不知道为什么截取的字符串是03-01 离谱  2017-03-01
    let m = date.substr(0,2);
    let d = birthday.substr(8,10);
    return "魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯".substr(m * 2 - (d < "102223444433".charAt(m - 1) - -19) * 2, 2);
  },
  /**
   * 随机产生6位数字
   */
  MathRand() {
    var Num = "";
    for (var i = 0; i < 6; i++) {
      Num += Math.floor(Math.random() * 10);
    }
    return Num;
  },
  /**
   * 根据日期计算年了
   * @param {} strAge 
   */
  getAge(strAge) {
    var birArr = strAge.split("-");
    var birYear = birArr[0];
    var birMonth = birArr[1];
    var birDay = birArr[2];

    d = new Date();
    var nowYear = d.getFullYear();
    var nowMonth = d.getMonth() + 1; //记得加1
    var nowDay = d.getDate();
    var returnAge;

    if (birArr == null) {
      return false
    };
    var d = new Date(birYear, birMonth - 1, birDay);
    if (d.getFullYear() == birYear && (d.getMonth() + 1) == birMonth && d.getDate() == birDay) {
      if (nowYear == birYear) {
        returnAge = 0; // 
      } else {
        var ageDiff = nowYear - birYear; // 
        if (ageDiff > 0) {
          if (nowMonth == birMonth) {
            var dayDiff = nowDay - birDay; // 
            if (dayDiff < 0) {
              returnAge = ageDiff - 1;
            } else {
              returnAge = ageDiff;
            }
          } else {
            var monthDiff = nowMonth - birMonth; // 
            if (monthDiff < 0) {
              returnAge = ageDiff - 1;
            } else {
              returnAge = ageDiff;
            }
          }
        } else {
          return "出生日期晚于今天，数据有误"; //返回-1 表示出生日期输入错误 晚于今天
        }
      }
      return returnAge;
    } else {
      return ("输入的日期格式错误！");
    }
  }
})